
import requests
import json

def send_dingtalk_message(webhook_url, message, at_mobiles=None, is_at_all=False):
    """
    发送消息到钉钉群组

    :param webhook_url: 钉钉机器人的Webhook地址
    :param message: 要发送的消息内容
    :param at_mobiles: 需要@的手机号列表，默认为None
    :param is_at_all: 是否@所有人，默认为False
    """
    headers = {
        'Content-Type': 'application/json'
    }

    data = {
        "msgtype": "text",
        "text": {
            "content": message
        },
        "at": {
            "atMobiles": at_mobiles if at_mobiles else [],
            "isAtAll": is_at_all
        }
    }

    response = requests.post(webhook_url, headers=headers, data=json.dumps(data))
    if response.status_code == 200:
        result = response.json()
        if result.get('errcode') == 0:
            print("消息发送成功")
        else:
            print(result)
    else:
        print(f"请求失败，状态码: {response.status_code}")

if __name__ == "__main__":
    # 替换为你的钉钉机器人Webhook地址
    webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=4acb6a45c1a4a3277ed7cbb8dfed5ee0b549866f91f4f2a80e08f7ed14368ea2"
    message = "这是一条测试消息，@所有人"
    at_mobiles = ['123456']  # 不需要@特定的人
    is_at_all = False # @所有人

    send_dingtalk_message(webhook_url, message, at_mobiles, is_at_all)